package com.quyeying.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import cn.hutool.poi.excel.StyleSet;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.quyeying.entity.*;
import com.quyeying.entity.vo.ExportWaitShipOrderVo;
import com.quyeying.entity.vo.ReceiveVo;
import com.quyeying.enums.SysConfigConstant;
import com.quyeying.enums.TblOrderBaseEnum;
import com.quyeying.enums.TblOrderStatusRecordEnum;
import com.quyeying.mapper.TblOrderBaseDao;
import com.quyeying.service.*;
import com.quyeying.utils.IdGeneratorSnowflake;
import com.quyeying.utils.RedisUtil;
import com.quyeying.utils.TokenUtil;
import com.quyeying.utils.jackson.JsonUtils;
import com.quyeying.utils.result.R;
import com.quyeying.utils.result.ResultEnum;
import com.quyeying.utils.result.ReturnPageData;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.poi.ss.usermodel.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单基础信息表 服务实现类
 * </p>
 *
 * @author skx
 * @since 2022-07-19
 */
@Slf4j
@Service
public class TblOrderBaseServiceImpl extends ServiceImpl<TblOrderBaseDao, TblOrderBaseEntity> implements TblOrderBaseService {

    @Resource
    ObjectMapper objectMapper;
    @Resource
    TblOrderStatusRecordService orderStatusRecordService;
    @Resource
    TblOrderProductService orderProductService;
    @Resource
    IdGeneratorSnowflake idGeneratorSnowflake;
    @Resource
    TblProductService productService;
    @Resource
    WxService wxService;
    @Resource
    RedisUtil redisUtil;
    @Resource
    TblProductSkuService productSkuService;
    @Resource
    TblFollowMerchantService tblFollowMerchantService;
    @Resource
    TblUserService userService;
    @Resource
    TblGiftReceiveService giftReceiveService;
    @Resource
    TblAddressService tblAddressService;

    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


    @Override
    public R findListByPage(Integer page, Integer pageCount, Integer orderStatus, String search, String searchType, String orderType, Long id, String sort, String startTime, String endTime) {
        IPage<TblOrderBaseEntity> wherePage = new Page<>(page, pageCount);
        QueryWrapper<TblOrderBaseEntity> where = new QueryWrapper<>();
        where.eq("merchant_id", id);
        if (ObjectUtils.isNotEmpty(orderStatus)) {
            //查询订单状态为6时，查询的为待售后的订单
            int status = 6;
            if (orderStatus != status) {
                where.eq("order_status", orderStatus);
            } else {
                where.eq("pay_status", 2);
            }
        }
        if (ObjectUtils.isNotEmpty(orderType)) {
            where.eq("type", orderType);
        }
        if (ObjectUtils.isNotEmpty(search)) {
            //0按电话号码   1按单号   不传类型，两种都查
            if (ObjectUtils.isNotEmpty(searchType)) {
                if ("0".equals(searchType)) {
                    where.and(qw -> qw.like("consignee_phone", search));
                } else if ("1".equals(searchType)) {
                    where.and(qw -> qw.like("order_no", search));
                }
            } else {
                where.and(qw -> qw.like("consignee_phone", search).or().like("order_no", search));
            }
        }
        where.apply(startTime != null&&startTime != "", "date_format (create_time,'%Y-%m-%d') >= date_format ({0},'%Y-%m-%d')", startTime)
                .apply(endTime != null&&endTime != "", "date_format (create_time,'%Y-%m-%d') <= date_format ({0},'%Y-%m-%d')", endTime);
        if ("0".equals(sort)||ObjectUtils.isEmpty(sort)){
            where.orderByDesc("create_time");
        }else if ("1".equals(sort)||ObjectUtils.isEmpty(sort)){
            where.orderByAsc("create_time");
        }

        IPage<TblOrderBaseEntity> iPage = baseMapper.selectPage(wherePage, where);
        return R.success(ReturnPageData.fillingData(iPage));
    }

    /**
     * 根据用户id查询订单列表
     *
     * @param request     request
     * @param page        页码
     * @param pageCount   每页条数
     * @param orderStatus 订单状态
     * @return R
     */
    @Override
    public R findListByPage(HttpServletRequest request, Integer page, Integer pageCount, Integer orderStatus) {
        long userId = TokenUtil.getUserId(request);
        IPage<TblOrderBaseEntity> wherePage = new Page<>(page, pageCount);

        QueryWrapper<TblOrderBaseEntity> where = new QueryWrapper<>();
        where.eq("user_id", userId);
        if (ObjectUtils.isNotEmpty(orderStatus)) {
            if (TblOrderBaseEnum.ORDER_STATUS_IV.getStatusCode().equals(orderStatus)) {
                where.and(item ->
                        item.eq("order_status", orderStatus)
                                .or()
                                .eq("order_status", TblOrderBaseEnum.ORDER_STATUS_V.getStatusCode())
                                .or()
                                .eq("order_status", TblOrderBaseEnum.ORDER_STATUS_VI.getStatusCode())
                                .or()
                                .eq("order_status", TblOrderBaseEnum.ORDER_STATUS_VII.getStatusCode())
                );
            } else {
                where.eq("order_status", orderStatus);
            }
        }
        IPage<TblOrderBaseEntity> iPage = baseMapper.selectPage(wherePage, where.orderByDesc("id"));
        iPage.getRecords().forEach(item -> {
            List<TblOrderProductEntity> orderProductAndBrowse = orderProductService.getOrderProductAndBrowse(item.getId());
            item.setOrderProductEntities(orderProductAndBrowse);
            //领取信息
            if (item.getType() == 1) {
                setReceiveInfo(item);
            }
        });
        return R.success(ReturnPageData.fillingData(iPage));
    }

    @Override
    public R add(TblOrderBaseEntity tblOrderBaseEntity) {
        baseMapper.insert(tblOrderBaseEntity);
        return R.success();
    }

    @Override
    public R delete(Long id) {
        baseMapper.deleteById(id);
        return R.success();
    }

    @Override
    public R updateData(TblOrderBaseEntity tblOrderBaseEntity) {
        baseMapper.updateById(tblOrderBaseEntity);
        return R.success();
    }

    @Override
    public R findById(Long id) {

        TblOrderBaseEntity tblOrderBaseEntity = baseMapper.selectById(id);

        //获取订单商品信息列表
        QueryWrapper<TblOrderProductEntity> orderProductEntityQueryWrapper = new QueryWrapper<>();
        orderProductEntityQueryWrapper.select("product_id, product_name, product_extend_I, product_extend_II, " +
                        "product_image, product_no, product_unit_price")
                .eq("order_id", id);
        List<TblOrderProductEntity> orderProductList = orderProductService.list(orderProductEntityQueryWrapper);
        //处理商品浏览量
        orderProductList = orderProductList.stream().map(item -> {
            TblProductEntity product = productService.getById(item.getProductId());
            item.setProductBrowse(product.getProductBrowse());
            return item;
        }).collect(Collectors.toList());

        //获取订单状态记录信息
        QueryWrapper<TblOrderStatusRecordEntity> orderStatusRecordEntityQueryWrapper = new QueryWrapper<>();
        orderStatusRecordEntityQueryWrapper.select("order_status, create_time").eq("order_id", id);
        List<TblOrderStatusRecordEntity> orderStatusRecordList = orderStatusRecordService.list(orderStatusRecordEntityQueryWrapper);

        //是否可以自领礼品单判断
        if(tblOrderBaseEntity.getOrderStatus().intValue() == TblOrderBaseEnum.ORDER_STATUS_II.getStatusCode()) {
            QueryWrapper<TblGiftReceiveEntity> giftReceiveQueryWrapper = new QueryWrapper<>();
            giftReceiveQueryWrapper.eq("from_id", tblOrderBaseEntity.getId());
            List<TblGiftReceiveEntity> receiveEntities = giftReceiveService.list(giftReceiveQueryWrapper);
            QueryWrapper<TblOrderProductEntity> orderProductQueryWrapper = new QueryWrapper<>();
            orderProductQueryWrapper.select("COALESCE(sum(product_no)) as giftNum, product_unit_price as productUnitPrice").eq("order_id", tblOrderBaseEntity.getId());
            Map<String, Object> productMap = orderProductService.getMap(orderProductQueryWrapper);
            //礼物数量
            int giftNum = Integer.parseInt(productMap.get("giftNum").toString());
            long countDown = tblOrderBaseEntity.getCreateTime().getTime() + 129600000L - System.currentTimeMillis();
            tblOrderBaseEntity.setShowSelfReceive(false);
            if (receiveEntities.size() < giftNum && countDown <= 0 && tblOrderBaseEntity.getSelfReceive() == 0) {
                tblOrderBaseEntity.setShowSelfReceive(true);
            }
        }

        Map<String, Object> resMap = new HashMap<>(6);
        resMap.put("orderBaseInfo", tblOrderBaseEntity);
        resMap.put("orderProductList", orderProductList);
        resMap.put("orderStatusRecordList", orderStatusRecordList);
        //领取信息
        List<Map<String, Object>> receiveList = baseMapper.selectReceiveByIdList(tblOrderBaseEntity.getId());
        QueryWrapper<TblOrderProductEntity> tblOrderProductEntityQueryWrapper = new QueryWrapper<>();
        tblOrderProductEntityQueryWrapper.eq("order_id", tblOrderBaseEntity.getId());
        TblOrderProductEntity orderProductEntity = orderProductService.getOne(tblOrderProductEntityQueryWrapper);
        Map<String, Object> receive = new HashMap<>(3);
        receive.put("receiveNum", receiveList.size());//已经领取
        receive.put("unclaimedNum", orderProductEntity.getProductNo() - receiveList.size());//待领取
        receive.put("countNum", orderProductEntity.getProductNo());
        resMap.put("receive", receive);
        long countDown = tblOrderBaseEntity.getCreateTime().getTime() + 129600000L - System.currentTimeMillis();
        if (countDown <= 0) {
            countDown = -1L;
        }
        resMap.put("countDown", countDown);
        resMap.put("timeStamp", tblOrderBaseEntity.getCreateTime().getTime());
        String timeout = sdf.format(tblOrderBaseEntity.getCreateTime().getTime() + 129600000L);
        resMap.put("timeout", timeout);
        if (tblOrderBaseEntity.getType() == 2) {
            //查询这个订单的留言
            QueryWrapper<TblGiftReceiveEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("to_id", id).eq("recetive_user", tblOrderBaseEntity.getUserId());
            TblGiftReceiveEntity giftReceiveEntity = giftReceiveService.getOne(queryWrapper);
            Map<String, Object> giftReceiveMap = new HashMap<>(2);
            giftReceiveMap.put("leaveMsg", giftReceiveEntity.getLeaveMsg());
            TblUserEntity tblUserEntity = userService.getById(giftReceiveEntity.getRecetiveUser());
            giftReceiveMap.put("nickName", tblUserEntity.getNickName());
            resMap.put("giftReceiveMap", giftReceiveMap);
        }
        return R.success(resMap);
    }

    /**
     * 发货
     *
     * @param orderBaseEntity
     */
    @Override
    public void ship(TblOrderBaseEntity orderBaseEntity) {
        orderBaseEntity.setOrderStatus(TblOrderBaseEnum.ORDER_STATUS_III.getStatusCode());
        baseMapper.updateById(orderBaseEntity);
        //新增订单状态记录信息
        orderStatusRecordService.addOrderStatusRecord(orderBaseEntity.getId(), TblOrderStatusRecordEnum.ORDER_STATUS_III.getStatusCode());
    }

    /**
     * 导出待发货订单数据
     */
    @Override
    public void exportWaitShipOrderInfo(HttpServletResponse response, Long id, @RequestBody Map<String, Object> reqParam) {
        List<ExportWaitShipOrderVo> waitShipOrderData = baseMapper.getWaitShipOrderData(id, reqParam);
        formatValue(waitShipOrderData);
        //在内存操作，写到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);
        //定义头部样式
        StyleSet style = writer.getStyleSet();
        CellStyle cellStyle = style.getHeadCellStyle();
        Font font = writer.createFont();
        //设置字体名称 宋体 / 微软雅黑 /等
        font.setFontName("微软雅黑");
        //设置是否斜体
        font.setItalic(false);
        //设置字体大小 以磅为单位
        font.setFontHeightInPoints((short) 14);
        //设置是否加粗
        font.setBold(true);
        cellStyle.setFont(font);
        cellStyle.setFillForegroundColor(IndexedColors.GREEN.getIndex());

        //自定义标题别名
        writer.addHeaderAlias("createTime", "下单时间");
        writer.addHeaderAlias("type", "订单类型");
        writer.addHeaderAlias("orderStatus", "订单状态");
        writer.addHeaderAlias("transactionId", "微信订单号");
        writer.addHeaderAlias("orderNo", "订单号");
        writer.addHeaderAlias("payerTotal", "付款金额/元");
        writer.addHeaderAlias("consigneeName", "收货人名称");
        writer.addHeaderAlias("consigneePhone", "联系电话");
        writer.addHeaderAlias("consigneeAddr", "收货地址");
        writer.addHeaderAlias("freight", "运费/元");
        writer.addHeaderAlias("productImage", "商品图片");
        writer.addHeaderAlias("productName", "产品名称");
        writer.addHeaderAlias("productSku", "产品规格");
        writer.addHeaderAlias("productNo", "购买数量");
        writer.addHeaderAlias("productUnitPrice", "单价/元");
        writer.setOnlyAlias(true);

        //合并
        LinkedHashMap<String, List<ExportWaitShipOrderVo>> map = waitShipOrderData.stream().collect(Collectors.groupingBy(item -> item.getId().toString(), LinkedHashMap::new, Collectors.toList()));

        int firstRow = 1, lastRow;
        for (List<ExportWaitShipOrderVo> orderVoList : map.values()) {
            int size = orderVoList.size();
            lastRow = firstRow + size - 1;
            if (size > 1) {
                for (int i = 0; i <= 10; i++) {
                    writer.merge(firstRow, lastRow, i, i, null, true);
                }
            }
            firstRow = firstRow + size;
        }
        //导出
        writer.write(waitShipOrderData, true);

//        for (int i = 0; i < orderVos.size(); i++) {
//            //读取图片
////            byte[] pictureData = FileUtil.readBytes("https://dss2.bdstatic.com/8_V1bjqh_Q23odCf/pacific/1992030914.jpg");
//            //写入图片
//            writePic(writer, 8, i+1, orderVos.get(i).getProductImage(), HSSFWorkbook.PICTURE_TYPE_JPEG);
//        }

        //列宽自适应
        Sheet sheet = writer.getSheet();
        //默认取第一行数据，解决中文自适应宽度不足问题
        if (sheet != null && sheet.getRow(1) != null) {
            int physicalNumberOfCells = sheet.getRow(1).getPhysicalNumberOfCells();
            for (int i = 0; i < physicalNumberOfCells; i++) {
                // 调整每一列宽度
                sheet.autoSizeColumn((short) i);
                // 解决自动设置列宽中文失效的问题
                sheet.setColumnWidth(i, sheet.getColumnWidth(i) * 17 / 10);
            }
        }

        //设置content—type
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset:utf-8");

        //设置标题
        String fileName = null;
        try {
            fileName = URLEncoder.encode("待发货订单记录".concat(DateUtil.format(new Date(), "YYYYMMddHHmmss")), "UTF-8");
            //Content-disposition是MIME协议的扩展，MIME协议指示MIME用户代理如何显示附加的文件。
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
            ServletOutputStream outputStream = response.getOutputStream();
            //将Writer刷新到OutPut
            writer.flush(outputStream, true);
            outputStream.close();
            writer.close();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void formatValue(List<ExportWaitShipOrderVo> waitShipOrderData) {
        waitShipOrderData.forEach(item -> {
            if (Integer.parseInt(item.getOrderStatus()) == TblOrderBaseEnum.ORDER_STATUS_I.getStatusCode()) {
                item.setOrderStatus(TblOrderBaseEnum.ORDER_STATUS_I.getStatusText());
            } else if (Integer.parseInt(item.getOrderStatus()) == TblOrderBaseEnum.ORDER_STATUS_II.getStatusCode()) {
                item.setOrderStatus(TblOrderBaseEnum.ORDER_STATUS_II.getStatusText());
            } else if (Integer.parseInt(item.getOrderStatus()) == TblOrderBaseEnum.ORDER_STATUS_III.getStatusCode()) {
                item.setOrderStatus(TblOrderBaseEnum.ORDER_STATUS_III.getStatusText());
            } else if (Integer.parseInt(item.getOrderStatus()) == TblOrderBaseEnum.ORDER_STATUS_IV.getStatusCode()) {
                item.setOrderStatus(TblOrderBaseEnum.ORDER_STATUS_IV.getStatusText());
            } else if (Integer.parseInt(item.getOrderStatus()) == TblOrderBaseEnum.ORDER_STATUS_V.getStatusCode()) {
                item.setOrderStatus(TblOrderBaseEnum.ORDER_STATUS_V.getStatusText());
            } else if (Integer.parseInt(item.getOrderStatus()) == TblOrderBaseEnum.ORDER_STATUS_VI.getStatusCode()) {
                item.setOrderStatus(TblOrderBaseEnum.ORDER_STATUS_VI.getStatusText());
            } else if (Integer.parseInt(item.getOrderStatus()) == TblOrderBaseEnum.ORDER_STATUS_VII.getStatusCode()) {
                item.setOrderStatus(TblOrderBaseEnum.ORDER_STATUS_VII.getStatusText());
            }
            String orderType = Integer.parseInt(item.getType()) == TblOrderBaseEnum.ORDER_TYPE_I.getStatusCode() ? TblOrderBaseEnum.ORDER_TYPE_I.getStatusText() : (Integer.parseInt(item.getType()) == TblOrderBaseEnum.ORDER_TYPE_II.getStatusCode() ? TblOrderBaseEnum.ORDER_TYPE_II.getStatusText() : TblOrderBaseEnum.ORDER_TYPE_III.getStatusText());
            item.setType(orderType);
        });
    }

    /**
     * 创建订单
     *
     * @param request
     * @param params
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public R createOrder(HttpServletRequest request, Map<String, Object> params) {
        //获取要购买的商品信息
        if (ObjectUtils.isNotEmpty(params.get("goods"))) {
            try {
                List<TblOrderProductEntity> goods = objectMapper.readValue(JsonUtils.toJsonString(params.get("goods")), new TypeReference<List<TblOrderProductEntity>>() {
                });

                //计算订单总金额
                List<Map<String, Object>> priceList = new ArrayList<>();
                goods.forEach(item -> {
                    //设置订单商品信息
                    TblProductEntity tblProductEntity = productService.tblProductEntity(item.getProductId(), false, "");
                    TblProductSkuEntity skuEntity = productSkuService.getById(item.getProductSkuId());
                    //验证库存
                    if (ObjectUtils.isEmpty(skuEntity) || item.getProductNo().compareTo(skuEntity.getProductStock()) > 0) {
                        throw new RuntimeException(ResultEnum.PRODUCT_STOCK_INSUFFICIENT.getMsg());
                    }
                    String productImage = "";
                    if (tblProductEntity.getTblProductImageEntityList().size() > 0) {
                        productImage = tblProductEntity.getTblProductImageEntityList().get(0).getImageUrl();
                    }
                    //扣除库存
                    reduceStock(skuEntity, item.getProductNo());
                    item.setProductId(tblProductEntity.getId());
                    item.setProductImage(productImage);
                    item.setProductName(tblProductEntity.getProductName());
                    item.setProductUnitPrice(skuEntity.getPrice());
                    item.setProductExtendI(skuEntity.getSkuName());
                    item.setProductExtendIi(skuEntity.getId().toString());

                    QueryWrapper<TblProductSkuEntity> skuEntityQueryWrapper = new QueryWrapper<>();
                    skuEntityQueryWrapper.select("(price * " + item.getProductNo() + ") as price")
                            .eq("id", skuEntity.getId());
                    priceList.add(productSkuService.getMap(skuEntityQueryWrapper));
                });
                BigDecimal productPrice = priceList.stream().map(e -> (BigDecimal) e.get("price")).reduce(BigDecimal.ZERO, BigDecimal::add);
                //创建订单
                TblOrderBaseEntity orderBaseEntity = new TblOrderBaseEntity()
                        .setUserId(TokenUtil.getUserId(request))
                        .setMerchantId(Long.valueOf(params.get("merchantId").toString()))
                        .setType((Integer) params.get("type"))
                        .setOrderNo(String.valueOf(idGeneratorSnowflake.snowflakeId()))
                        .setConsigneeAddr(ObjectUtils.isNotEmpty(params.get("consigneeAddr")) ? params.get("consigneeAddr").toString() : null)
                        .setConsigneeName(params.get("consigneeName").toString())
                        .setConsigneePhone(params.get("consigneePhone").toString())
                        .setPayerTotal(productPrice);
                baseMapper.insert(orderBaseEntity);

                orderProductService.saveBatch(goods.stream().peek(item -> item.setOrderId(orderBaseEntity.getId())).collect(Collectors.toList()));
                orderStatusRecordService.addOrderStatusRecord(orderBaseEntity.getId(), TblOrderBaseEnum.ORDER_STATUS_I.getStatusCode());
//              生成小程序拉取微信支付参数
                Map<String, Object> map = wxService.miniJsapi(orderBaseEntity);
                map.put("orderId", orderBaseEntity.getId());
//              缓存到redis一小时
                redisUtil.set(SysConfigConstant.SYS_PREFIX.concat(orderBaseEntity.getOrderNo()), orderBaseEntity.getOrderNo(), 3600);
                return R.success(map);
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException("下单失败");
            }
        }

        return R.error(ResultEnum.SYSTEM_ERROR);
    }

    /**
     * 扣除库存
     */
    private void reduceStock(TblProductSkuEntity skuEntity, Integer reduceNum) {

        UpdateWrapper<TblProductSkuEntity> productEntityQueryWrapper = new UpdateWrapper<>();
        productEntityQueryWrapper.eq("id", skuEntity.getId())
                .eq("product_stock", skuEntity.getProductStock());

        skuEntity.setProductStock(skuEntity.getProductStock() - reduceNum);
        if (!productSkuService.update(skuEntity, productEntityQueryWrapper) || skuEntity.getProductStock() < 0) {
            throw new RuntimeException("库存扣除失败");
        }
    }

    /**
     * 订单取消还原库存
     */
    @Override
    public void restoreStock(Long orderId) {

        QueryWrapper<TblOrderProductEntity> wrapper = new QueryWrapper<>();
        wrapper.select("product_id, product_no, product_extend_II").eq("order_id", orderId);
        List<TblOrderProductEntity> orderProductEntities = orderProductService.list(wrapper);
        orderProductEntities.forEach(item -> {
            restoreStock(item);
        });
    }

    /**
     * 撤销申请退款
     *
     * @param orderId
     * @return
     */
    @Override
    public R revokeRefund(Long orderId) {
        TblOrderBaseEntity orderBaseEntity = new TblOrderBaseEntity();
        orderBaseEntity.setId(orderId);
        orderBaseEntity.setPayStatus(TblOrderBaseEnum.PAY_STATUS_II.getStatusCode());
        orderBaseEntity.setOrderStatus(TblOrderBaseEnum.ORDER_STATUS_IV.getStatusCode());
        if (baseMapper.updateById(orderBaseEntity) > 0) {
            orderStatusRecordService.addOrderStatusRecord(orderId, 8);
        }
        return R.success();
    }

    public void restoreStock(TblOrderProductEntity orderProductEntity) {

        TblProductSkuEntity skuEntity = productSkuService.getById(orderProductEntity.getProductExtendIi());
        if (ObjectUtils.isNotEmpty(skuEntity)) {
            UpdateWrapper<TblProductSkuEntity> skuEntityUpdateWrapper = new UpdateWrapper<>();
            skuEntityUpdateWrapper.eq("id", skuEntity.getId())
                    .eq("product_stock", skuEntity.getProductStock());

            skuEntity.setProductStock(skuEntity.getProductStock() + orderProductEntity.getProductNo());
            if (!productSkuService.update(skuEntity, skuEntityUpdateWrapper)) {
                log.info("库存还原失败");
                restoreStock(orderProductEntity);
            }
        }
    }

    /**
     * 处理支付成功订单
     *
     * @param jsonNode
     */
    @Override
    public void processPaymentSuccessOrder(JsonNode jsonNode) {

        String outTradeNo = jsonNode.get("out_trade_no").textValue();
        String transactionId = jsonNode.get("transaction_id").textValue();
        //获取订单信息
        QueryWrapper<TblOrderBaseEntity> baseEntityQueryWrapper = new QueryWrapper<>();
        baseEntityQueryWrapper.eq("order_no", outTradeNo);
        TblOrderBaseEntity order = baseMapper.selectOne(baseEntityQueryWrapper);
        order.setTransactionId(transactionId);
        order.setOrderStatus(TblOrderBaseEnum.ORDER_STATUS_II.getStatusCode());
        order.setPayStatus(TblOrderBaseEnum.PAY_STATUS_II.getStatusCode());
        //更新订单信息
        baseMapper.updateById(order);
        //更新订单状态记录
        orderStatusRecordService.addOrderStatusRecord(order.getId(), 1);
        //移除取消订单标识--
        redisUtil.del(SysConfigConstant.SYS_PREFIX + order.getOrderNo());
    }

    /**
     * 确认收货
     *
     * @param orderId
     */
    @Override
    public void confirmOrder(long orderId) {
        TblOrderBaseEntity orderBaseEntity = new TblOrderBaseEntity();
        orderBaseEntity.setId(orderId);
        orderBaseEntity.setOrderStatus(TblOrderBaseEnum.ORDER_STATUS_IV.getStatusCode());
        baseMapper.updateById(orderBaseEntity);
        orderStatusRecordService.addOrderStatusRecord(orderId, TblOrderStatusRecordEnum.ORDER_STATUS_IV.getStatusCode());
    }

    /**
     * 审核退款
     *
     * @param request
     * @param jsonNode: {"orderId": 订单id, agreest: 0同意 1拒绝}
     * @return
     */
    @Override
    public R refund(HttpServletRequest request, JsonNode jsonNode) {
        long orderId = jsonNode.get("orderId").longValue();
        int agreest = jsonNode.get("agreest").intValue();
        TblOrderBaseEntity orderBaseEntity = baseMapper.selectById(orderId);
        //退款金额 = 退款金额-领取的金额
        BigDecimal refundMoney = baseMapper.getOrderReceiveMoney(orderBaseEntity.getId());
        orderBaseEntity.setRefundAmount(refundMoney);
        if (agreest == 1) {
            orderBaseEntity.setPayStatus(TblOrderBaseEnum.PAY_STATUS_V.getStatusCode());
            orderBaseEntity.setOrderStatus(TblOrderBaseEnum.ORDER_STATUS_IV.getStatusCode());
            updateById(orderBaseEntity);
            orderStatusRecordService.addOrderStatusRecord(orderId, TblOrderStatusRecordEnum.ORDER_STATUS_VIII.getStatusCode());
            return R.success();
        }
        //发起退款
        refund(orderBaseEntity);
        return R.success();
    }

    @Override
    public R cancelOrder(long orderId, int cancelType) {
        TblOrderBaseEntity orderBaseEntity = baseMapper.selectById(orderId);
        //送礼订单被领取完不让退
        if (orderBaseEntity.getType() == 1) {
            //领取记录
            QueryWrapper<TblGiftReceiveEntity> giftReceiveEntityQueryWrapper = new QueryWrapper<>();
            giftReceiveEntityQueryWrapper.eq("from_id", orderId);
            int receiveCount = giftReceiveService.count(giftReceiveEntityQueryWrapper);
            QueryWrapper<TblOrderProductEntity> tblOrderProductEntityQueryWrapper = new QueryWrapper<>();
            tblOrderProductEntityQueryWrapper.eq("order_id", orderBaseEntity.getId());
            TblOrderProductEntity orderProductEntity = orderProductService.getOne(tblOrderProductEntityQueryWrapper);
            if (orderProductEntity.getProductNo() == receiveCount) {
                return R.error(ResultEnum.SYSTEM_ERROR.getCode(), "礼物被领取完了，无法退款！");
            }
        }
        if (cancelType == 0) {
            orderBaseEntity.setOrderStatus(TblOrderBaseEnum.ORDER_STATUS_V.getStatusCode());
            baseMapper.updateById(orderBaseEntity);
            orderStatusRecordService.addOrderStatusRecord(orderId, TblOrderStatusRecordEnum.ORDER_STATUS_V.getStatusCode());
            redisUtil.del(SysConfigConstant.SYS_PREFIX + orderBaseEntity.getOrderNo());
            //还原库存
            restoreStock(orderId);
        } else if (cancelType == 1) {
            orderBaseEntity.setRefundAmount(orderBaseEntity.getPayerTotal());
            //送礼订单被领取完不让退
            if (orderBaseEntity.getType() == 1) {
                //退款金额 = 退款金额-领取的金额
                BigDecimal refundMoney = baseMapper.getOrderReceiveMoney(orderBaseEntity.getId());
                orderBaseEntity.setRefundAmount(refundMoney);
            }
            refund(orderBaseEntity);
        } else {
            orderBaseEntity.setOrderStatus(TblOrderBaseEnum.ORDER_STATUS_VII.getStatusCode());
            orderBaseEntity.setPayStatus(TblOrderBaseEnum.PAY_STATUS_III.getStatusCode());
            baseMapper.updateById(orderBaseEntity);
            orderStatusRecordService.addOrderStatusRecord(orderId, TblOrderStatusRecordEnum.ORDER_STATUS_VI.getStatusCode());
        }
        return R.success();
    }

    /**
     * 发起退款
     */
    private void refund(TblOrderBaseEntity orderBaseEntity) {
        try {
            JsonNode refund = wxService.refund(orderBaseEntity.getTransactionId(), orderBaseEntity.getPayerTotal(), orderBaseEntity.getRefundAmount());
            log.info(refund + "+++++++++++");
            if (refund.has("refund_id")) {
                orderBaseEntity.setOrderStatus(TblOrderBaseEnum.ORDER_STATUS_VI.getStatusCode());
                orderBaseEntity.setPayStatus(TblOrderBaseEnum.PAY_STATUS_IV.getStatusCode());
                orderBaseEntity.setRefundId(refund.get("refund_id").textValue());
                orderBaseEntity.setOutRefundNo(refund.get("out_refund_no").textValue());
                baseMapper.updateById(orderBaseEntity);
                orderStatusRecordService.addOrderStatusRecord(orderBaseEntity.getId(), TblOrderStatusRecordEnum.ORDER_STATUS_VII.getStatusCode());
                //还原库存
                restoreStock(orderBaseEntity.getId());
                return;
            }
            throw new RuntimeException(ResultEnum.UNKNOWN_ERROR.getMsg());
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("退款失败！".concat(e.getMessage()));
        }

    }


    /**
     * 线上图片转为byte数组
     *
     * @param path
     * @return
     */
    public static byte[] onlineImage2byte(String path) throws IOException {
        byte[] data = null;
        URL url = null;
        InputStream input = null;
        try {
            url = new URL(path);
            HttpURLConnection httpUrl = (HttpURLConnection) url.openConnection();
            httpUrl.connect();
            httpUrl.getInputStream();
            input = httpUrl.getInputStream();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        int numBytesRead = 0;
        while ((numBytesRead = input.read(buf)) != -1) {
            output.write(buf, 0, numBytesRead);
        }
        data = output.toByteArray();
        output.close();
        input.close();
        return data;
    }

    /**
     * @param writer
     * @param x           单元格x轴坐标
     * @param y           单元格y轴坐标
     * @param pictureData 图片二进制数据
     * @param picType     图片格式
     */
    private void writePic(ExcelWriter writer, int x, int y, byte[] pictureData, int picType) {
        Sheet sheet = writer.getSheet();
        Drawing drawingPatriarch = sheet.createDrawingPatriarch();

        //设置图片单元格位置
        ClientAnchor anchor = drawingPatriarch.createAnchor(0, 0, 0, 0, x, y, x + 1, y + 1);
        //随单元格改变位置和大小
        anchor.setAnchorType(ClientAnchor.AnchorType.MOVE_AND_RESIZE);

        //添加图片
        int pictureIndex = sheet.getWorkbook().addPicture(pictureData, picType);
        drawingPatriarch.createPicture(anchor, pictureIndex);
    }


    @Override
    public R findOrderTypeNum(HttpServletRequest request) {
        long userId = TokenUtil.getUserId(request);
        Map<String, Object> map = new HashMap<>();
        QueryWrapper<TblOrderBaseEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_status", 0).eq("user_id", userId);
        map.put("toBePaid", baseMapper.selectCount(queryWrapper));
        queryWrapper.clear();
        queryWrapper.eq("order_status", 1).eq("user_id", userId);
        map.put("toBeShipped", baseMapper.selectCount(queryWrapper));
        queryWrapper.clear();
        queryWrapper.eq("order_status", 2).eq("user_id", userId);
        map.put("toBeReceived", baseMapper.selectCount(queryWrapper));
        QueryWrapper<TblFollowMerchantEntity> merchantEntityQueryWrapper = new QueryWrapper<>();
        merchantEntityQueryWrapper.eq("user_id", userId);
        map.put("followNum", tblFollowMerchantService.count(merchantEntityQueryWrapper));
        return R.success(map);
    }

    @Override
    public Integer getUnreadNum(long userId) {
        return baseMapper.getUnreadNum(userId);
    }

    @Override
    public R getReceiveGiftData(HttpServletRequest request, Long orderId) {
        Map<String, Object> resMap = new HashMap<>(5);
        resMap.put("status", 0);
        //获取送礼订单数据
        TblOrderBaseEntity orderBase = getById(orderId);
        if (orderBase.getOrderStatus().equals(TblOrderBaseEnum.ORDER_STATUS_VI)) {
            resMap.put("status", 1);
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long countDown = 0;
        try {
            countDown = sdf.parse(sdf.format(orderBase.getCreateTime())).getTime() + 129600000L - System.currentTimeMillis();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (countDown < 0) {
            countDown = -1L;
            resMap.put("status", 2);
        } else {
            //礼物被抢光了or已经领取过了
            QueryWrapper<TblGiftReceiveEntity> giftReceiveQueryWrapper = new QueryWrapper<>();
            giftReceiveQueryWrapper.eq("from_id", orderBase.getId());
            List<TblGiftReceiveEntity> receiveEntities = giftReceiveService.list(giftReceiveQueryWrapper);
            QueryWrapper<TblOrderProductEntity> orderProductQueryWrapper = new QueryWrapper<>();
            orderProductQueryWrapper.select("COALESCE(sum(product_no)) as giftNum").eq("order_id", orderBase.getId());
            Map<String, Object> productMap = orderProductService.getMap(orderProductQueryWrapper);
            if (receiveEntities.size() == Integer.parseInt(productMap.get("giftNum").toString())) {
                resMap.put("status", 1);
            } else {
                if (TokenUtil.verfiyToken(request)) {
                    receiveEntities.forEach(item -> {
                        if (item.getRecetiveUser() == TokenUtil.getUserId(request)) {
                            resMap.put("status", 3);
                        }
                    });
                }
            }
        }
        resMap.put("countDown", countDown);
        resMap.put("timeStamp", orderBase.getCreateTime().getTime());
        //送礼人名称
        QueryWrapper<TblUserEntity> userEntityQueryWrapper = new QueryWrapper<>();
        userEntityQueryWrapper.select("nick_name as nickName").eq("id", orderBase.getUserId());
        TblUserEntity user = userService.getOne(userEntityQueryWrapper);
        resMap.put("nickName", user.getNickName());
        return R.success(resMap);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public R receiveGifts(HttpServletRequest request, Long orderId, Map<String, Object> params) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        TblOrderBaseEntity orderBase = getById(orderId);
        if (TokenUtil.getUserId(request) == orderBase.getUserId()) {
            return R.error(ResultEnum.SYSTEM_ERROR.getCode(), "无法领取自己的礼品");
        }
        long countDown = 0;
        try {
            if (orderBase.getPayStatus() == 3) {
                return R.error(ResultEnum.SYSTEM_ERROR.getCode(), "礼物被抢光");
            }
            countDown = sdf.parse(sdf.format(orderBase.getCreateTime())).getTime() + 129600000L - System.currentTimeMillis();
            if (countDown < 0) {
                return R.error(ResultEnum.INVALID_INVITE_CODE);
            }
            //礼物被抢光了or已经领取过了
            QueryWrapper<TblGiftReceiveEntity> giftReceiveQueryWrapper = new QueryWrapper<>();
            giftReceiveQueryWrapper.eq("from_id", orderBase.getId());
            List<TblGiftReceiveEntity> receiveEntities = giftReceiveService.list(giftReceiveQueryWrapper);
            QueryWrapper<TblOrderProductEntity> orderProductQueryWrapper = new QueryWrapper<>();
            orderProductQueryWrapper.select("COALESCE(sum(product_no)) as giftNum, product_unit_price as productUnitPrice").eq("order_id", orderBase.getId());
            Map<String, Object> productMap = orderProductService.getMap(orderProductQueryWrapper);
            //礼物数量
            int giftNum = Integer.parseInt(productMap.get("giftNum").toString());
            if (receiveEntities.size() == giftNum) {
                return R.error(ResultEnum.SYSTEM_ERROR.getCode(), "礼物被抢光");
            } else {
                for (TblGiftReceiveEntity item : receiveEntities
                ) {
                    if (item.getRecetiveUser() == TokenUtil.getUserId(request)) {
                        return R.error(ResultEnum.SYSTEM_ERROR.getCode(), "请勿重复领取");
                    }
                }
            }
            //生成子订单
            orderProductQueryWrapper.clear();
            orderProductQueryWrapper.eq("order_id", orderBase.getId());
            //TODO 当前一个单只有一个商品
            TblOrderProductEntity orderProduct = orderProductService.getOne(orderProductQueryWrapper);
            TblOrderBaseEntity orderBaseEntity = new TblOrderBaseEntity()
                    .setUserId(TokenUtil.getUserId(request))
                    .setMerchantId(orderBase.getMerchantId())
                    .setOrderNo(String.valueOf(idGeneratorSnowflake.snowflakeId()))
                    .setTransactionId(orderBase.getTransactionId())
                    .setConsigneeAddr(params.get("addressProvince").toString()+params.get("addressCity").toString()
                            +params.get("addressArea").toString()+params.get("addressDetails").toString())
                    .setConsigneeName(params.get("addressName").toString())
                    .setConsigneePhone(params.get("addressPhone").toString())
                    .setOrderStatus(TblOrderBaseEnum.ORDER_STATUS_II.getStatusCode())
                    .setPayStatus(TblOrderBaseEnum.PAY_STATUS_II.getStatusCode())
                    .setPayerTotal(orderProduct.getProductUnitPrice())
                    //新增收礼订单状态
                    .setType(2);
            baseMapper.insert(orderBaseEntity);
            //插入到订单商品表
            orderProduct.setId(null);
            orderProduct.setOrderId(orderBaseEntity.getId());
            //这里把领取数量改为1，一人只能领取一分
            orderProduct.setProductNo(1);
            orderProductService.add(orderProduct);
            orderStatusRecordService.addOrderStatusRecord(orderBaseEntity.getId(), TblOrderStatusRecordEnum.ORDER_STATUS_II.getStatusCode());
            //生成领取记录
            TblGiftReceiveEntity giftReceiveEntity = new TblGiftReceiveEntity()
                    .setFromId(orderBase.getId())
                    .setToId(orderBaseEntity.getId())
                    .setRecetiveUser(TokenUtil.getUserId(request))
                    .setReceiveTime(new Date());
            giftReceiveService.add(giftReceiveEntity);
            if(giftNum - (receiveEntities.size()+1) == 0) {
                //领光更新送礼订单状态为已完成
                orderBase.setOrderStatus(TblOrderBaseEnum.ORDER_STATUS_IV.getStatusCode());
                updateById(orderBase);
            }
            Map<String, Object> map = new HashMap<>(2);
            map.put("orderId", orderBaseEntity.getId());
            map.put("giftId", giftReceiveEntity.getId());
            //如果领取人第一次领取礼物，保存收礼人地址信息并设为默认
            QueryWrapper<TblAddressEntity> addressEntityQueryWrapper = new QueryWrapper<>();
            addressEntityQueryWrapper.eq("user_id", TokenUtil.getUserId(request));
            int addressCount = tblAddressService.count(addressEntityQueryWrapper);
            if (addressCount==0){
                TblAddressEntity tblAddressEntity = new TblAddressEntity();
                tblAddressEntity.setAddressName(params.get("addressName").toString());
                tblAddressEntity.setAddressPhone(params.get("addressPhone").toString());
                tblAddressEntity.setAddressProvince(params.get("addressProvince").toString());
                tblAddressEntity.setAddressCity(params.get("addressCity").toString());
                tblAddressEntity.setAddressArea(params.get("addressArea").toString());
                tblAddressEntity.setAddressDetails(params.get("addressDetails").toString());
                tblAddressEntity.setDefaultStatus(1);
                tblAddressService.add(tblAddressEntity,request);
            }
            return R.success(map);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return R.error(ResultEnum.SYSTEM_ERROR);
    }

    @Override
    public R getReceiveGiftsList(HttpServletRequest request, Integer current, Integer size) {
        QueryWrapper<TblGiftReceiveEntity> giftReceiveQueryWrapper = new QueryWrapper<>();
        giftReceiveQueryWrapper.select("to_id as orderId").eq("recetive_user", TokenUtil.getUserId(request));
        List<Object> orderIds = giftReceiveService.listObjs(giftReceiveQueryWrapper);
        if (ObjectUtils.isNotEmpty(orderIds)) {
            IPage<TblOrderBaseEntity> wherePage = new Page<>(current, size);
            QueryWrapper<TblOrderBaseEntity> where = new QueryWrapper<>();
            where.in("id", orderIds);
            IPage<TblOrderBaseEntity> iPage = baseMapper.selectPage(wherePage, where.orderByDesc("id"));
            iPage.getRecords().forEach(item -> {
                List<TblOrderProductEntity> orderProductAndBrowse = orderProductService.getOrderProductAndBrowse(item.getId());
                item.setOrderProductEntities(orderProductAndBrowse);
            });
            return R.success(ReturnPageData.fillingData(iPage));
        }
        return R.success(ReturnPageData.fillingData(new Page<>()));
    }

    @Override
    public R getGiveGiftsList(HttpServletRequest request, Integer current, Integer size) {
        IPage<TblOrderBaseEntity> wherePage = new Page<>(current, size);
        QueryWrapper<TblOrderBaseEntity> where = new QueryWrapper<>();
        where.eq("type", 1).eq("user_id", TokenUtil.getUserId(request));
        IPage<TblOrderBaseEntity> iPage = baseMapper.selectPage(wherePage, where.orderByDesc("id"));
        iPage.getRecords().forEach(item -> {
            List<TblOrderProductEntity> orderProductAndBrowse = orderProductService.getOrderProductAndBrowse(item.getId());
            item.setOrderProductEntities(orderProductAndBrowse);
            //领取记录
            setReceiveInfo(item);
        });
        return R.success(ReturnPageData.fillingData(iPage));
    }

    /**
     * set礼物订单领取信息
     * @param orderInfo
     */
    private void setReceiveInfo(TblOrderBaseEntity orderInfo) {
        //是否可以自领礼品单判断
        if(orderInfo.getOrderStatus().intValue() == TblOrderBaseEnum.ORDER_STATUS_II.getStatusCode()) {
            QueryWrapper<TblGiftReceiveEntity> giftReceiveQueryWrapper = new QueryWrapper<>();
            giftReceiveQueryWrapper.eq("from_id", orderInfo.getId());
            List<TblGiftReceiveEntity> receiveEntities = giftReceiveService.list(giftReceiveQueryWrapper);
            QueryWrapper<TblOrderProductEntity> orderProductQueryWrapper = new QueryWrapper<>();
            orderProductQueryWrapper.select("COALESCE(sum(product_no)) as giftNum, product_unit_price as productUnitPrice").eq("order_id", orderInfo.getId());
            Map<String, Object> productMap = orderProductService.getMap(orderProductQueryWrapper);
            //礼物数量
            int giftNum = Integer.parseInt(productMap.get("giftNum").toString());
            long countDown = orderInfo.getCreateTime().getTime() + 129600000L - System.currentTimeMillis();
            orderInfo.setShowSelfReceive(false);
            if (receiveEntities.size() < giftNum && countDown <= 0 && orderInfo.getSelfReceive() == 0) {
                orderInfo.setShowSelfReceive(true);
            }
        }
        List<Map<String, Object>> receiveList = baseMapper.selectReceiveByIdList(orderInfo.getId());
        QueryWrapper<TblOrderProductEntity> tblOrderProductEntityQueryWrapper = new QueryWrapper<>();
        tblOrderProductEntityQueryWrapper.eq("order_id", orderInfo.getId());
        TblOrderProductEntity orderProductEntity = orderProductService.getOne(tblOrderProductEntityQueryWrapper);
        ReceiveVo receiveVo = new ReceiveVo();
        receiveVo.setReceiveNum(receiveList.size());
        receiveVo.setUnclaimedNum(orderProductEntity.getProductNo() - receiveList.size());
        receiveVo.setCountNum(orderProductEntity.getProductNo());
        orderInfo.setReceiveVo(receiveVo);
    }

    @Override
    public R getGiftCollectionList(Long id) {
        return R.success(baseMapper.selectReceiveByIdList(id));
    }

    @Override
    public R getSonOrderList(Long orderId) {
        QueryWrapper<TblGiftReceiveEntity> giftReceiveQueryWrapper = new QueryWrapper<>();
        giftReceiveQueryWrapper.select("to_id as orderId").eq("from_id", orderId);
        List<Object> orderIds = giftReceiveService.listObjs(giftReceiveQueryWrapper);
        if (ObjectUtils.isNotEmpty(orderIds)) {
            QueryWrapper<TblOrderBaseEntity> where = new QueryWrapper<>();
            where.in("id", orderIds);
            List<TblOrderBaseEntity> entityList = baseMapper.selectList(where.orderByDesc("id"));
            entityList.forEach(item -> {
                List<TblOrderProductEntity> orderProductAndBrowse = orderProductService.getOrderProductAndBrowse(item.getId());
                item.setOrderProductEntities(orderProductAndBrowse);
                TblUserEntity user = userService.getById(item.getUserId());
                item.setReceiveUser(user.getNickName());
            });
            return R.success(entityList);
        }
        return R.success(Collections.emptyList());
    }

    @Override
    public R orderUpdateState(HttpServletRequest request, Map<String, Object> params) {
        long userId = TokenUtil.getUserId(request);
        TblOrderBaseEntity tblOrderBase = baseMapper.selectById(Long.valueOf(params.get("orderId").toString()));
        if (tblOrderBase.getType()!=0||tblOrderBase.getUserId()!=userId
                ||tblOrderBase.getOrderStatus()!=1||tblOrderBase.getPayStatus()!=1){
            return R.error(ResultEnum.SYSTEM_ERROR);
        }
        //修改订单类型
        TblOrderBaseEntity tblOrderBaseEntity = new TblOrderBaseEntity();
        tblOrderBaseEntity.setId(Long.valueOf(params.get("orderId").toString())).setType(1);
        baseMapper.updateById(tblOrderBaseEntity);
        return R.success();
    }

    @Override
    public R orderUpdateAddress(HttpServletRequest request, Map<String, Object> params) {
        long userId = TokenUtil.getUserId(request);
        TblOrderBaseEntity tblOrderBase = baseMapper.selectById(Long.valueOf(params.get("orderId").toString()));
        if (ObjectUtils.isEmpty(tblOrderBase)||tblOrderBase.getType()!=1||tblOrderBase.getUserId()!=userId
                ||tblOrderBase.getOrderStatus()!=1||tblOrderBase.getPayStatus()!=1){
            return R.error(ResultEnum.SYSTEM_ERROR);
        }
        //修改订单地址,并且修改订单领取状态
        TblOrderBaseEntity orderBaseEntity = new TblOrderBaseEntity()
                .setUserId(userId)
                .setConsigneeAddr(params.get("addressProvince").toString()+params.get("addressCity").toString()
                        +params.get("addressArea").toString()+params.get("addressDetails").toString())
                .setConsigneeName(params.get("addressName").toString())
                .setConsigneePhone(params.get("addressPhone").toString())
                .setId(Long.valueOf(params.get("orderId").toString()))
                .setSelfReceive(1);
        baseMapper.updateById(orderBaseEntity);
        return R.success();
    }
}
